<template>
  <div class="user_container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 搜索框 -->
      <el-form>
        <el-input
          @keyup.enter.native="getList"
          clearable
          @clear="getUserList"
          @input="getList"
          v-model="pageinfo.query"
          placeholder="请输入内容"
          class="input-with-select"
        >
          <el-button
            @click="getUserList"
            slot="append"
            icon="el-icon-search"
          ></el-button>
        </el-input>
        <el-button type="primary" @click="showUserDialog">添加用户</el-button>
      </el-form>
      <!-- 用户表格 -->
      <el-table :data="userData" style="width: 100%" border>
        <el-table-column type="index" label="#" width="80"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <div>
              <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"> </el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <div>
              <!-- 编辑 -->
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click.prevent="editUserDia(scope.row)"
              ></el-button>

              <!-- 删除 -->
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="open(scope.row.id)"
              ></el-button>
              <!-- 分配 -->
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"      
                @click="setUserRoles(scope.row)"
              ></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格分页
        * 参数说明
        1. size-change：每页显示条数改变时会触发
        2. current-change：当前页码改变时触发
        3. page-sizes ：每页显示条数的数组
        4. page-size:默认每页显示条数
        5. layout：显示分页布局结构 
        6. total:总记录数
      
      
       -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageinfo.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="2"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>


       <!-- 编辑用户对话框 -->
      <el-dialog title="编辑用户" :visible.sync="isEditUser">
        <el-form :model="addUserDiaData" :rules="addUserDiaRules" ref="EditUserDia">
          <el-form-item label="用户名" label-width="120px" prop="username">
            <el-input disabled v-model="addUserDiaData.username"  autocomplete="off"></el-input>
          </el-form-item>
          

          <el-form-item label="邮箱" label-width="120px" prop="email">
            <el-input v-model="addUserDiaData.email"  autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="手机" label-width="120px" prop="mobile">
            <el-input v-model="addUserDiaData.mobile"  autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="isEditUser = false">取 消</el-button>
          <el-button type="primary" @click="EditUserConfirm"
            >确 定</el-button
          >
        </div>
      </el-dialog>

      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="isAddUser">
        <el-form :model="addUserDiaData" :rules="addUserDiaRules" ref="addUserDia">
          <el-form-item label="用户名" label-width="120px" prop="username">
            <el-input v-model="addUserDiaData.username"  autocomplete="off"></el-input>
          </el-form-item>
          

          <el-form-item label="密码" label-width="120px" prop="password">
            <el-input v-model="addUserDiaData.password"  autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" label-width="120px" prop="email">
            <el-input v-model="addUserDiaData.email"  autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="手机" label-width="120px" prop="mobile">
            <el-input v-model="addUserDiaData.mobile"  autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="isAddUser = false">取 消</el-button>
          <el-button type="primary" @click="addUserConfirm"
            >确 定</el-button
          >
        </div>
      </el-dialog>
     <!-- 修改角色弹窗 -->
        <el-dialog title="分配角色" :visible.sync="isSetRoleUser" width="40%">
          <p>当前用户：{{ currentUserInfo.username }}</p>
          <p style="margin:10px 0">当前角色：{{ currentUserInfo.role_name }}</p>
          分配新角色：
          <el-select
            v-model="currentRoleId"
          
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <span slot="footer" class="dialog-footer">
            <el-button @click="isSetRoleUser = false">取 消</el-button>
            <el-button type="primary" @click="setUserRoleOk">确 定</el-button
            >
          </span>
        </el-dialog>


    </el-card>
  </div>
</template>

<script>
import _ from "lodash";
    //邮箱验证规则
import { getUserListAPI,addUserAPI,EditUserAPI,DelUserAPI,StateUserAPI,RolesIdAPI,RoleUserAPI } from "@/http/api";
export default {
  name: "userlist",
  data() {
    //邮箱验证规则
    const checkEmail=(rule,value,callback)=>{
      const reg=/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/g;   //用户名@xxxx.com.cn
      if(!reg.test(value)) {
        return callback(new Error('邮箱不合法，请输入重新'))
      }
      callback();
    }
    //手机号验证规则
    const checkMobile=(rule,value,callback)=>{
      const reg=/^1(3|4|5|6|7|8|9)\d{9}$/g;
      if(!reg.test(value)) {
         return callback(new Error('手机号不合法，请输入重新手机号'))
      }
      callback()
    }
    return {
      //当前选择的角色id
      currentRoleId:'',
      // 角色列表
      roleList:[],
      //当前用户id
      currrentUserId:'',
      //编辑用户状态
      isEditUser:false,
      //当前用户
      currentUserInfo:{},
      //是否显示分配角色对话框
      isSetRoleUser:false,
      //添加用户对话框要绑定的数据
      addUserDiaData:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },

      //添加用户对话表单验证规则
      addUserDiaRules:{
        username:[
          {required:true,message:'请填写用户名',trigger:'blur'},
          {min:6,max:16,message:'请输入长度在6到16之间的字符个数',trigger:'blur'}
        ],
        password:[
            {required:true,message:'请填写密码',trigger:'blur'},
            {min:6,max:16,message:'请输入长度在6到16之间的字符个数',trigger:'blur'}
        ],
        email:[
            {required:true,message:'请填写邮箱',trigger:'blur'},
            {validator:checkEmail,trigger:'blur'}
        ],
        mobile:[
           {required:true,message:'请填写手机号',trigger:'blur'},
            {validator:checkMobile,trigger:'blur'}
        ]
      },
      //是否显示添加用户对话框
      isAddUser:false,
      flag: false,
      //用户列表
      userData: [],
      pageinfo: {
        //查询的关键字
        query: "",
        //当前页码
        pagenum: 1,
        //每页显示几条
        pagesize: 3,
      },
      total: 0,
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
      // 点击确定按钮分配角色给用户
   async setUserRoleOk(){
     const res = await RoleUserAPI(this.currrentUserId,{rid:this.currentRoleId})
  //关闭对话框
      this.isSetRoleUser = false;
    this.getUserList();

      },
     // 修改角色弹窗显示并把当前获取的那一条数据给到弹窗去渲染
    async setUserRoles(role) {
      this.currrentUserId = role.id
      console.log(role);
      //当前角色信息
      this.currentUserInfo = role;
      //调用角色列表接口
     const res = await RolesIdAPI()
      console.log('角色',res);
      this.roleList = res;

      //显示对话框
      this.isSetRoleUser = true;
    }, 
     
  // 根据Id删除对应的用户信息
  open(id) {
      console.log(id);
     this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });

          DelUserAPI(id).then(res=>{
             this.getUserList();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
        // 改变用户状态
     userStateChanged(state) {
      console.log(state);
      StateUserAPI(state.id,state.mg_state)
    },
    //确认修改用户
    EditUserConfirm() {
      //整体表单的验证
      this.$refs.EditUserDia.validate(async valid=>{
        if(!valid) return;
        //调后台接口，将新用户添加到向后台
        const res=await EditUserAPI(this.currrentUserId,this.addUserDiaData)
        //关闭对话框
        this.isEditUser=false
        //重新拉取用户列表
        this.getUserList()

      })
    },
    //打开编辑对话框
    editUserDia(user) {
      console.log('当前要编辑的用户：',user)
      //获取用户id
      this.currrentUserId=user.id
      //将当前user绑定到addUserDiaData上，从而同步到编辑对话框中
      this.addUserDiaData=user;
      //显示编辑对话框
      this.isEditUser=true
    
    },
    //确定要添加的用户
    addUserConfirm() {
      //整体表单的验证
      this.$refs.addUserDia.validate(async valid=>{
        if(!valid) return;

        //调后台接口，将新用户添加到向后台
        const res=await addUserAPI(this.addUserDiaData)
        console.log('添加的新用户：',res)

        //关闭对话框
        this.isAddUser=false
        //重新拉取用户列表
        this.getUserList()

      })
    },
    //显示添加用户对话框
    showUserDialog() {
      //清空对话框数据
    //  this.addUserDiaData={
    //     username:'',
    //     password:'',
    //     email:'',
    //     mobile:''
    //   }
      //显示对话框
      this.isAddUser=true;
    },
    //触发每页显示的条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageinfo.pagesize = val;
      this.getUserList();
    },
    //触发当前点击页码
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageinfo.pagenum = val;
      this.getUserList();
    },
    async getUserList() {
      //调用户列表接口
      const res = await getUserListAPI(this.pageinfo);
      console.log("用户列表：", res);
      let { total, users } = res;
      this.userData = users;
      this.total = total;
    },
    getList: _.throttle(function () {
      this.getUserList();
    }, 2000),
  },
};
</script>

<style lang="scss">
.el-breadcrumb {
  margin-bottom: 15px;
}

.el-card {
  box-shadow: 0 1px 1px 0 #ccc !important;
}

.input-with-select {
  width: 350px;
  margin-right: 20px;
}

.el-table {
  margin-top: 15px;
}
</style>